package com.hycat.mail.cart.service.impl;

import com.hycat.mail.cart.client.ProductClient;
import com.hycat.mail.cart.service.CartService;
import com.hycat.mail.cart.vo.Cart;
import com.hycat.mail.cart.vo.CartItem;
import com.hycat.mail.cart.vo.SkuInfoVo;
import com.hycat.mail.common.exception.MailException;
import com.hycat.mail.common.interceptor.AuthInterceptor;
import com.hycat.mail.common.model.ExceptionEnum;
import com.hycat.mail.common.model.JwtInfo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author 吕泽浩业
 * @version 1.0
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {
    private final static Logger logger = LoggerFactory.getLogger(CartServiceImpl.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ProductClient productClient;

    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public CartItem addCart(Long skuId, Integer count, JwtInfo jwtInfo) {
        //1.商品基本属性
        CartItem cartItem = new CartItem();
        CompletableFuture<Void> skuInfoFuture = CompletableFuture.runAsync(() -> {
            cartItem.from(productClient.skuInfo(skuId), count);
        }, executor);

        //2.商品销售属性
        CompletableFuture<Void> attrValueFuture = CompletableFuture.runAsync(() -> {
            List<String> strings = productClient.listSaleValue(skuId);
            cartItem.setSkuAttrs(strings);
        }, executor);

        CompletableFuture.allOf(skuInfoFuture, attrValueFuture).join();
        redisTemplate.opsForHash().put("cart:" + AuthInterceptor.threadLocal.get().getId(), skuId.toString(), cartItem);
        return cartItem;
    }

    @Override
    public Cart listCart(Long memberId) {
        Cart cart = new Cart();
        List<CartItem> values = redisTemplate.opsForHash().values("cart:" + memberId);
        List<CartItem> collect = values.stream()
                .sorted(Comparator.comparing(CartItem::getCreatTime))
                .collect(Collectors.toList());
        logger.info("本次拿到的map集合是 {}", collect);

        Integer totalNum = 0;
        BigDecimal totalPrice = new BigDecimal("0");
        for(int i = 0; i < collect.size(); i++) {
            totalNum += collect.get(i).getCount(); //总数量
            totalPrice = totalPrice.add(new BigDecimal(String.valueOf(collect.get(i).getTotalPrice())));
        }
        cart.setTotalNum(totalNum);
        cart.setTypeNum(collect.size());
        cart.setTotalPrice(totalPrice);
        cart.setReduce(new BigDecimal("0"));
        cart.setItems(collect);
        return cart;
    }

    @Override
    public Cart listOrderCart(Long memberId) {
        Cart cart = new Cart();
        //从Redis拿数据封装到
        Set<String> keys = redisTemplate.opsForHash().keys("cart:" + memberId);
        ArrayList<Long> list = new ArrayList<>();
        for (String s : keys) {
            list.add(Long.parseLong(s));
        }
        List<SkuInfoVo> skuInfoVos = productClient.listBySkuIds(list);

        Integer totalNum = 0;
        BigDecimal totalPrice = new BigDecimal("0");
        ArrayList<CartItem> collect = new ArrayList<>();
        for(int i = 0; i < skuInfoVos.size(); i++) {
            //查数据库最新sku + 数量 ——> 封装cartItem  ——> 加入collect
            CartItem cartItem = (CartItem) redisTemplate.opsForHash().get("cart:" + memberId, skuInfoVos.get(i).getSkuId().toString());
            CartItem newCartItem = new CartItem().from(skuInfoVos.get(i), cartItem.getCount());
            collect.add(newCartItem);
            redisTemplate.opsForHash().put("cart:" + memberId, skuInfoVos.get(i).getSkuId(), newCartItem);
            //库存不足 todo 拿到所有库存不足的 封装返回 并且删除
            if(!(newCartItem.getHasStock())) {
                throw new MailException(ExceptionEnum.ORDER_SKU_STOCK_NOT_ENOUGH, newCartItem.getSkuId());
            }
            //已经下架 todo 拿到所有下架的 封装返回 并且删除
            if(!newCartItem.getCheck()) {
                throw new MailException(ExceptionEnum.ORDER_SKU_CHECK_IS_FALSE, newCartItem.getSkuId());
            }
            totalNum += newCartItem.getCount(); //总数量
            totalPrice = totalPrice.add(new BigDecimal(String.valueOf(newCartItem.getTotalPrice())));
        }
        cart.setTotalNum(totalNum);
        cart.setTypeNum(skuInfoVos.size());
        cart.setTotalPrice(totalPrice);
        cart.setReduce(new BigDecimal("0"));
        cart.setItems(collect);
        return cart;
    }
}
